package com.carserver.controller;

import com.carserver.common.Result;
import com.carserver.pojo.User;
import com.carserver.service.UserDao;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserDao userDao;



    @PostMapping("/register")
    public Result register(@RequestBody User User) {
//        service.save(User);
        System.out.println(User.toString());
        if(userDao.findUserByEmail(User.getEmail())==null){
            System.out.println("11");
            userDao.save(User);
        }else {
            return Result.error("1","邮箱已被注册");
        }
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody User User) {
        System.out.println(User);
//        System.out.println(service.findByEmail(User.getEmail()));
//        System.out.println(service.findByPassword(User.getPassword()));
        User u=userDao.findUserByEmail(User.getEmail());
        if(u==null){
            return Result.error("1","邮箱未注册",User);
        }else{
            if(!u.getUserPwd().equals(User.getUserPwd())){
                System.out.println(u.getUserPwd());
                return Result.error("1","密码不正确",User);
            }
        }
        return Result.success(u);
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
            userDao.deleteById(id);
            return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody User user){
        userDao.save(user);
        return Result.success(user);
    }

    @GetMapping
    public Result<?> findPage(@RequestParam (defaultValue = "0")Integer pageNum,
                              @RequestParam (defaultValue = "10")Integer pageSize,
                              @RequestParam (defaultValue = "")String search){
        List<User> userPage = userDao.findUserByPage(pageNum,pageSize);
        return Result.success(userPage);
    }
//    @GetMapping
//    public Result<?> findPage(@RequestParam (defaultValue = "1")Integer pageNum,
//                              @RequestParam (defaultValue = "10")Integer pageSize,
//                              @RequestParam (defaultValue = "")String search){
//        Page<User> userPage = userDao.selectPage(new Page<>(pageNum, pageSize), Wrappers.<User>lambdaQuery().like(User::getId, search));
//        return Result.success(userPage);
//    }
}
